import axios from 'axios'
import { getRefreshToken, setToken, setRefreshToken } from '@/utils/auth'

// 创建axios实例
const apiClient = axios.create({
  baseURL: '/api',  // 基础URL
  timeout: 30000  // 增加超时时间到30秒（RAG系统可能需要更多时间）
  // 不设置默认Content-Type，让axios根据数据类型自动设置
})

// 请求拦截器 - 自动添加token
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
      // 调试日志
      if (config.url?.includes('identity')) {
        console.log('🔑 Adding token to request:', {
          url: config.url,
          hasToken: !!token,
          tokenLength: token.length,
          authHeader: config.headers.Authorization?.substring(0, 30) + '...'
        })
      }
    } else {
      console.warn('⚠️ No token found in localStorage')
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理401错误并自动刷新Token
apiClient.interceptors.response.use(
  (response) => {
    return response
  },
  async (error) => {
    const originalRequest = error.config
    
    // 401错误时尝试刷新Token（Token续命）
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true
      
      // 排除刷新接口和登录接口，避免死循环
      if (originalRequest.url?.includes('/auth/refresh') || originalRequest.url?.includes('/auth/login')) {
        localStorage.clear()
        alert('登录已过期，请重新登录')
        window.location.href = '/login'
        return Promise.reject(error)
      }
      
      // 尝试刷新Token
      const refresh_token = getRefreshToken()
      if (refresh_token) {
        try {
          const response = await axios.post('/api/auth/refresh', { refresh_token })
          const { access_token, refresh_token: new_refresh_token } = response.data
          setToken(access_token)
          setRefreshToken(new_refresh_token)
          // 用新Token重试原请求
          originalRequest.headers.Authorization = `Bearer ${access_token}`
          return apiClient(originalRequest)
        } catch {
          // 刷新失败，跳转登录
          localStorage.clear()
          alert('登录已过期，请重新登录')
          window.location.href = '/login'
        }
      }
    }
    return Promise.reject(error)
  }
)

export default apiClient
